import {
  Request,
  Response,
  Router,
} from 'express';

import { EnumStatusCode } from '@shared/constant/enum';
import { IExam } from '@shared/types/exam';

import {
  Exam,
  ExamRecord,
} from '../models/exam.model';
import { Paper } from '../models/paper.model';

export const examRouter = Router();

// 获取考试活动列表（支持分页和筛选）
examRouter.get("/list", async (req: Request, res: Response) => {
  try {
    const {
      page = 1,
      pageSize = 20,
      status,
      creator,
      keyword
    } = req.query;

    const filter: any = {};
    if (status) filter.is_enabled = status === 'enabled';
    if (creator) filter.creator = creator;
    if (keyword) {
      filter.exam_name = { $regex: keyword, $options: 'i' };
    }

    const limit = parseInt(pageSize as string);
    const skip = (parseInt(page as string) - 1) * limit;

    const exams = await Exam.find(filter)
      .populate('creator', 'username')
      .populate('paper', 'paper_name duration total_score')
      .skip(skip)
      .limit(limit)
      .sort({ create_time: -1 });

    const total = await Exam.countDocuments(filter);

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "success",
      data: {
        data: exams,
        total_records: total,
        page: parseInt(page as string),
        limit,
        total_page: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取考试活动列表失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "服务器内部错误",
      data: null
    });
  }
});

// 获取可参加的活动列表 考试端
examRouter.get("/available", async (req: Request, res: Response) => {
  console.log("enter /exam/available");

  try {
    const { page = 1, limit = 10 } = req.query;
    const skip = (Number(page) - 1) * Number(limit);
    const now = new Date();

    // 查询可参加的考试：状态为可用且在有效时间范围内
    const query = {
      is_enabled: true,
      start_time: { $lte: now },
      end_time: { $gte: now }
    };
    console.log('query======>',query);
    
    // 执行查询（不使用分页，因为需要先过滤参与人数）
    const allExams = await Exam.find(query)
      .populate('creator', 'username')
      .populate('paper', 'paper_name total_score question_list')
      .sort({ start_time: 1 });

    // 过滤掉已达到参与人数限制的考试
    const availableExams = [];
    for (const exam of allExams) {
      // 如果 participation_limit 为 0 或未定义，表示无限制
      if (!exam.participation_limit || exam.participation_limit === 0) {
        availableExams.push(exam);
        continue;
      }

      // 查询当前考试的参与人数（已完成的考试记录数）
      const participantCount = await ExamRecord.countDocuments({
        exam_id: exam._id,
        status: 'completed'
      });

      // 如果参与人数未达到限制，则加入可用列表
      if (participantCount < (exam.participation_limit || 0)) {
        availableExams.push(exam);
      }
    }

    // 手动实现分页
    const total = availableExams.length;
    const paginatedExams = availableExams.slice(skip, skip + Number(limit));

    console.log("total available exams", total);
    return res.json({
      code: EnumStatusCode.SUCCESS,
      message: "success",
      data: {
        list: paginatedExams,
        pagination: {
          total,
          page: Number(page),
          limit: Number(limit),
          totalPages: Math.ceil(total / Number(limit))
        }
      }
    });
  } catch (error) {
    console.error('获取可参加考试列表失败:', error);
    return res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "服务器内部错误",
      data: null
    });
  }
});

examRouter.get("/:id", async (req: Request, res: Response) => {

  console.log("enter /exam/:id")

  try {
    const { id } = req.params;
    const exam = await Exam.findById(id)
      .populate('creator', 'username')
      .populate({
        path: 'paper',
        populate: {
          path: 'question_list',
          select: 'content type options score difficulty'
        }
      });

    if (!exam) {
      return res.status(EnumStatusCode.NOT_FOUND).json({
        code: EnumStatusCode.NOT_FOUND,
        message: "考试活动不存在",
        data: null
      });
    }

    return res.json({
      code: EnumStatusCode.SUCCESS,
      message: "success",
      data: exam
    });
  } catch (error) {
    console.error('通过ID获取考试活动详情失败:', error);
    return res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "服务器内部错误",
      data: null
    });
  }
});

// 创建考试活动
examRouter.post("/create", async (req: Request, res: Response) => {
  try {
    const examData: Partial<IExam> = req.body;
    
    // 验证必填字段
    if (!examData.exam_name || !examData.paper || !examData.start_time || !examData.end_time) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "活动名称、试卷、开始时间和结束时间为必填项",
        data: null
      });
    }

    // 验证时间逻辑
    const startTime = new Date(examData.start_time);
    const endTime = new Date(examData.end_time);
    if (endTime <= startTime) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "结束时间必须晚于开始时间",
        data: null
      });
    }

    // 验证试卷是否存在
    const paper = await Paper.findById(examData.paper);
    if (!paper) {
      return res.status(EnumStatusCode.NOT_FOUND).json({
        code: EnumStatusCode.NOT_FOUND,
        message: "指定的试卷不存在",
        data: null
      });
    }

    const newExam = new Exam({
      ...examData,
      create_time: new Date(),
      creator: req.user?.user_id
    });

    await newExam.save();

    const savedExam = await Exam.findById(newExam._id)
      .populate('creator', 'username')
      .populate('paper', 'paper_name duration total_score');

    res.status(EnumStatusCode.CREATED).json({
      code: EnumStatusCode.CREATED,
      message: "考试活动创建成功",
      data: savedExam
    });
  } catch (error) {
    console.error('创建考试活动失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "服务器内部错误",
      data: null
    });
  }
});

// 更新考试活动
examRouter.put("/:id", async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const updateData: Partial<IExam> = req.body;

    // 如果更新时间，验证时间逻辑
    if (updateData.start_time && updateData.end_time) {
      const startTime = new Date(updateData.start_time);
      const endTime = new Date(updateData.end_time);
      if (endTime <= startTime) {
        return res.status(EnumStatusCode.BAD_REQUEST).json({
          code: EnumStatusCode.BAD_REQUEST,
          message: "结束时间必须晚于开始时间",
          data: null
        });
      }
    }

    // 如果更新试卷，验证试卷是否存在
    if (updateData.paper) {
      const paper = await Paper.findById(updateData.paper);
      if (!paper) {
        return res.status(EnumStatusCode.NOT_FOUND).json({
          code: EnumStatusCode.NOT_FOUND,
          message: "指定的试卷不存在",
          data: null
        });
      }
    }

    const updatedExam = await Exam.findByIdAndUpdate(
      id,
      { ...updateData, update_time: new Date() },
      { new: true, runValidators: true }
    )
      .populate('creator', 'username')
      .populate('paper', 'paper_name duration total_score');

    if (!updatedExam) {
      return res.status(EnumStatusCode.NOT_FOUND).json({
        code: EnumStatusCode.NOT_FOUND,
        message: "考试活动不存在",
        data: null
      });
    }

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "考试活动更新成功",
      data: updatedExam
    });
  } catch (error) {
    console.error('更新考试活动失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "服务器内部错误",
      data: null
    });
  }
});

// 删除考试活动
examRouter.delete("/:id", async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    
    const deletedExam = await Exam.findByIdAndDelete(id);
    
    if (!deletedExam) {
      return res.status(EnumStatusCode.NOT_FOUND).json({
        code: EnumStatusCode.NOT_FOUND,
        message: "考试活动不存在",
        data: null
      });
    }

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "考试活动删除成功",
      data: null
    });
  } catch (error) {
    console.error('删除考试活动失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "服务器内部错误",
      data: null
    });
  }
});

// 批量删除考试活动
examRouter.delete("/batch/:ids", async (req: Request, res: Response) => {
  try {
    const { ids } = req.params;
    const idArray = ids.split(',');

    const result = await Exam.deleteMany({
      _id: { $in: idArray }
    });

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: `成功删除 ${result.deletedCount} 个考试活动`,
      data: { deletedCount: result.deletedCount }
    });
  } catch (error) {
    console.error('批量删除考试活动失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "服务器内部错误",
      data: null
    });
  }
});

// 启用/禁用考试活动
examRouter.patch("/:id/status", async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { is_enabled } = req.body;

    const updatedExam = await Exam.findByIdAndUpdate(
      id,
      { is_enabled, update_time: new Date() },
      { new: true }
    )
      .populate('creator', 'username')
      .populate('paper', 'paper_name duration total_score');

    if (!updatedExam) {
      return res.status(EnumStatusCode.NOT_FOUND).json({
        code: EnumStatusCode.NOT_FOUND,
        message: "考试活动不存在",
        data: null
      });
    }

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: `考试活动已${is_enabled ? '启用' : '禁用'}`,
      data: updatedExam
    });
  } catch (error) {
    console.error('更新考试活动状态失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "服务器内部错误",
      data: null
    });
  }
});

// 获取可用试卷列表（用于创建考试时选择）
examRouter.get("/available/papers", async (req: Request, res: Response) => {
  try {
    const papers = await Paper.find({ status: 'published' })
      .select('paper_name duration total_score question_list')
      .populate('question_list');

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "success",
      data: papers
    });
  } catch (error) {
    console.error('获取可用试卷列表失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "服务器内部错误",
      data: null
    });
  }
});

// 获取考试排名
examRouter.get("/:id/ranking", async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    
    // 验证考试活动是否存在
    const exam = await Exam.findById(id);
    if (!exam) {
      return res.status(EnumStatusCode.NOT_FOUND).json({
        code: EnumStatusCode.NOT_FOUND,
        message: "考试活动不存在",
        data: null
      });
    }

    // 获取该考试的所有已完成记录，按分数排序
    const records = await ExamRecord.find({
      exam_id: id,
      status: 'completed'
    })
      .populate('user_id', 'username')
      .sort({ user_score: -1, submit_time: 1 }) // 分数高的在前，相同分数时提交早的在前
      .exec();

    // 构建排名数据
    const rankings = records.map((record: any, index: number) => ({
      _id: record._id, // 添加考试记录ID
      user_id: record.user_id._id,
      username: record.user_id.username,
      score: record.user_score || 0, // 使用 user_score 字段
      total_score: record.total_score || 0,
      rank: index + 1,
      submit_time: record.submit_time,
    }));

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "success",
      data: {
        rankings
      }
    });
  } catch (error) {
    console.error('获取考试排名失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "服务器内部错误",
      data: null
    });
  }
});

export default examRouter;